<?
    header('Content-type: text/html; charset=utf-8');
    $error = 0;
    $errormessage = '';
    if (isset($_GET['error'])) {
        $error = $_GET['error'];
    }
    if ($error != '0') {
        $error = 1;
        $errormessage = 'test error message';
    }
    $userid = -1;
    if (isset($_GET['userid'])) {
        $userid = $_GET['userid'];
    }
    $connection = mysql_connect ('localhost', 'zorik_if039', '9731')
    or die ('Unable to connect!');
    mysql_select_db('zorik_if039') or die (mysql_error());
    mysql_query("set character_set_client='utf8'"); 
    mysql_query("set character_set_server='utf8'"); 
    mysql_query("set character_set_results='utf8'"); 
    mysql_query("set collation_connection='utf8_unicode_ci'");
    $where = "";
    if ($userid != -1) {
        $where = " where id='$userid'";
    }
    $query = "SELECT user.password, user.nickname, user.email, user.id, count(photo.user_id) photostotal FROM user
left join photo on (photo.user_id = user.id) ".$where.
" group by password, nickname, email, id
order by photostotal desc";
    $res = mysql_query($query) or die(mysql_error());
    $rows = array();
    while($r = mysql_fetch_assoc($res)) {
        $rows[] = $r;
    }
    if ($error == 0) {
        $userList = (object) array('error' => $error, 'errormessage' => $errormessage, 'data' => $rows);
        for ($i = 0; $i < count($userList -> data); $i++) {
            $user_id = $userList -> data[$i]['id'];
            $query2 = "SELECT category.title title, count(photo.categoryid) count, photo.user_id id 
            FROM category
            join photo on photo.categoryid=category.id
            where (photo.user_id='$user_id')
            group by category.title, photo.user_id";
            $res2 = mysql_query($query2) or die(mysql_error());
            $user = array();
            while($r2 = mysql_fetch_assoc($res2)) {
                $user[] = $r2;
            }
            if (count($user) > 0) {
                $userList -> data[$i]['photos'] = (object) array('data' => $user);
            } else {
                $userList -> data[$i]['photos'] = (object) array('data' => '');
            }
        }
    } else {
        $userList = (object) array('error' => $error, 'errormessage' => $errormessage, 'data' => '');
    }
    echo json_encode($userList);
    mysql_close($connection);
?>